package gw.com.android.ui.news;

import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gwtsz.gts2.hx.R;

import java.util.List;

import gw.com.android.presenter.http.ReferenceRequest;

/**
 * @author jett
 * @since 2018-08-31.
 */
public class ReferenceAdapter extends RecyclerView.Adapter<ReferenceAdapter.ReferenceHolder> {

    private final Activity mActivity;
    private List<ReferenceRequest.Data> mDatas;

    ReferenceAdapter(Activity activity) {
        this.mActivity = activity;
    }

    public void update(List<ReferenceRequest.Data> list) {
        this.mDatas = list;
        notifyDataSetChanged();
    }

    public void append(List<ReferenceRequest.Data> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        if (mDatas == null) {
            mDatas = list;
        } else {
            mDatas.addAll(list);
        }
        notifyDataSetChanged();
    }

    @Override
    public ReferenceHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_reference, parent, false);
        return new ReferenceHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ReferenceHolder holder, int position) {
        ReferenceRequest.Data item = getItem(position);
        if (item == null) {
            return;
        }
        holder.tvTitle.setText(item.title);
        holder.tvTag.setText(item.label);
        holder.tvTime.setText(item.release_time);
        Glide.with(mActivity).load(item.cover_img).into(holder.ivImage);
    }

    private ReferenceRequest.Data getItem(int position) {
        if (mDatas != null && mDatas.size() > position) {
            return mDatas.get(position);
        }
        return null;
    }

    @Override
    public int getItemCount() {
        if (mDatas != null) {
            return mDatas.size();
        }
        return 0;
    }

    class ReferenceHolder extends RecyclerView.ViewHolder {

        TextView tvTitle;
        TextView tvTag;
        TextView tvTime;
        ImageView ivImage;

        ReferenceHolder(View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.reference_title);
            tvTag = itemView.findViewById(R.id.reference_tag);
            tvTime = itemView.findViewById(R.id.reference_time);
            ivImage = itemView.findViewById(R.id.reference_image);
        }

    }

}
